<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
  html { height: 100% }
  body { height: 100%; margin: 0px; padding: 0px }
  #map_canvas { height: 100% }
</style>
<script type="text/javascript"
    src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript">
var sharedLat = 35.133246;
var sharedLng = -90.041542;
var sharedRad = 100;
var sharedFilter = "";
var map;
var geocoder;
var markersArray = [];
var infowindowArray = [];
var EXPIRE_TIME = 30000;
var UPDATE_TIME = 2000;
var TextBoxStream = "";
var TextBox = "";
var lastTweet = "";

function initialize() {
	var latlng = new google.maps.LatLng(sharedLat, sharedLng);
	geocoder = new google.maps.Geocoder();
	var myOptions = {
		zoom: 8,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map_canvas"),
		myOptions);
/*
	google.maps.event.addListener(map, 'click', function(event) {
		sharedLat = event.latLng.lat();
		sharedLng = event.latLng.lng();

		var tmp = event.latLng;
		addMarker(tmp, tmp.toString(), tmp.toString());
	});
*/

	getEvents();
	
	setInterval("addNewMarkers()", 2000);
	setInterval("removeOldMarkers()", 5000);
}

function addMarker(location, title, message, imageURL, fbEventTF) {
	var image = new  google.maps.MarkerImage(imageURL, new google.maps.Size(64, 64));
	var marker = new google.maps.Marker({
		position: location,
		map: map,
		title: title,
		icon: image
	});

	var infowindow = new google.maps.InfoWindow(
		{ content:message,
		size: new google.maps.Size(50,50)
		});
	infowindowArray.push(infowindow);
	
	google.maps.event.addListener(marker, 'click', function() {
		infowindow.open(map,marker);
		
		var i = 0;
		for (i = 0; i < infowindowArray.length; i++)	{
			if (infowindowArray[i] == infowindow)
				continue;
			else
				infowindowArray[i].close();
		}
	});
	
	var timestamp = new Date().getTime();
	
	// store markers in array
	var tmpArr = [];
	tmpArr.push(marker);
	tmpArr.push(timestamp);
	tmpArr.push(fbEventTF);
	markersArray.push(tmpArr);
}

function codeAddress() {
	var address = document.getElementById("address").value;
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var location = results[0].geometry.location;			
			map.setCenter(location);
			sharedLat = location.lat();
			sharedLng = location.lng();
		} else {
			alert("Geocode was not successful for the following reason: " + status);
		}
	});
}

function transLoc2LatLng(addr, user, text, image, fbEvent)	{
	geocoder.geocode( { 'address': addr}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			addMarker(results[0].geometry.location, user, text, image, fbEvent);
			TextBoxStream = text + "<br>";
		
		}
	});
}

function getTwits(lati, longi, rad, filter)
{
	$.getJSON("http://search.twitter.com/search.json?callback=?",
	{
		rpp: "20",
		geocode: lati + "," + longi + "," + rad + "mi",
		q: filter
	},
	function(data) {
		$.each(data.results, function(r, result) {
			if(result.text != lastTweet)
			{	
				lastTweet = result.text;
				var loc = result.location;
				if(/[^0-9\-\+]*([-+]?[0-9]+(\.[0-9]+)?[^\,]*[,][^0-9\-\+]*[-+]?[0-9]+(\.[0-9]+)?).*/.test(loc))
				{
					loc = loc.replace(/[^0-9\-\+]*([-+]?[0-9]+(\.[0-9]+)?[^\,]*[,][^0-9\-\+]*[-+]?[0-9]+(\.[0-9]+)?).*/, "$1");
					addMarker(new google.maps.LatLng(parseFloat(loc.replace(/(.*)[,](.*)/, "$1")), parseFloat(loc.replace(/(.*)[,](.*)/, "$2"))), result.from_user, "<a href=\"http://twitter.com/" + result.from_user + "\">" + result.from_user + "</a><br>" + result.text, result.profile_image_url, false);
				}
				else
					transLoc2LatLng(loc, result.from_user, "<a href=\"http://twitter.com/" + result.from_user + "\">" + result.from_user + "</a><br>" + result.text, result.profile_image_url, false);
			}
		});
	});
	if (TextBoxStream != "")
		WriteTextValue();
};

function getEvents()
{
	FB.api(
		{
			method: 'fql.query',
			query: 'SELECT name, location, venue, pic, start_time, end_time FROM event WHERE eid IN (SELECT eid FROM event_member WHERE uid = me())'
		},
		function(response) {
			for(var i = 0; i < response.length; i++)
			{
				if(response[i].venue.street)
					addMarker(new google.maps.LatLng(response[i].venue.latitude, response[i].venue.longitude), response[i].name, response[i].name + " @ " + response[i].location, response[i].pic, true);
				else
					transLoc2LatLng(response[i].location, response[i].name, response[i].name + " @ " + response[i].location, response[i].pic, true);
			}
		}
	);
}

function addNewMarkers()	{
	getTwits(sharedLat, sharedLng, sharedRad, sharedFilter);
}

function removeOldMarkers() {
	var i = 0;
	for (i = 0; i < markersArray.length; i++)	{
		var marker = markersArray[i];
		markerTime = marker[1]
		
		timeNow = new Date().getTime();
		
		if ((timeNow - markerTime) > EXPIRE_TIME )	{
			if (marker[2] == false)	{
				marker[0].setMap(null);
			}
		}
	}	
}

// update stream box
function WriteTextValue() {
	TextBox = document.getElementById("scroll_box");
	TextBox.innerHTML = TextBoxStream + TextBox.innerHTML;
}

function setRadius() {
	var tmp = document.getElementById("radius").value;
	
	if (tmp <= 0)
		sharedRad = tmp;
	else (tmp > 100)
		sharedRad = 100;
}

function filterTweets()	{
	sharedFilter = document.getElementById("filter").value;
}

// debug...
function debug_print (msg)	{
	document.write(msg + "<br>");
}



</script>
</head>
<body onload="initialize()">

	<table>
	<tr>
		<td>		
			<div>
				<input id="address" type="textbox" value="San Francisco, CA">
				<input type="button" value="Enter" onclick="codeAddress()">
			</div>		
		</td>
		<td>
			<div>
				<input id="radius" type="textbox" value="100">
				<input type="button" value="Enter (miles)" onclick="setRadius()">
			</div>
		
		</td>
		<td>
			<div>
				<input id="filter" type="textbox" value="Enter filter keyword here">
				<input type="button" value="Enter" onclick="filterTweets()">
			</div>
		
		</td>
	</tr>

	</table>

	<div id="map_canvas" style="width:100%; height:70%"></div>
	


	
	<!-- Updating Scrolling Text Box -->
	<div id="scroll_box" style="height:20%;width:100%;font:12px/26px Georgia, Garamond, Serif; overflow-x:hidden; overflow-y:auto">
	</div>
	
	<fb:login-button perms="user_events,friends_events" autologoutlink="true"></fb:login-button>

	<div id="fb-root"></div>
	<script>
      window.fbAsyncInit = function() {
        FB.init({appId: '129214890487293', status: true, cookie: true,
                 xfbml: true});
        FB.Event.subscribe('{% if current_user %}auth.logout{% else %}auth.login{% endif %}', function(response) {
          window.location.reload();
        });
      };
      (function() {
        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>

</body>
</html>